package com.sofa.common.Interceptors;

import cn.hutool.core.util.StrUtil;
import com.sofa.common.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 最开始加这个拦截器,是为了将当前用户id传递到permission模块
 * 因为权限升降级的权限校验最开始我是在permission模块在实现的
 * 后续才发现demo要求里面写了要在user模块就校验,于是这个拦截器就没什么用了
 * 但是写都写了,就别删了吧
 */
@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取登录用户信息
        String userInfo = request.getHeader("user-info");

        log.info("UserInfoInterceptor拦截请求..............");
        //2.判断是否获取了用户,如果有,存入ThreadLocal
        if(StrUtil.isNotBlank(userInfo)){
            log.info("设置当前用户id:{}", userInfo);
            BaseContext.setCurrentId(Long.valueOf(userInfo));
        }

        //3.无论是否获取到当前用户都放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理用户
        BaseContext.removeCurrentId();
    }

}
